package com.feri.tiantian.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.feri.tiantian.config.RedisConfig;
import com.feri.tiantian.dao.SmsLogDao;
import com.feri.tiantian.entity.SmsLog;
import com.feri.tiantian.service.intf.SmsLogService;
import com.feri.tiantian.utils.AliSmsUtil;
import com.feri.tiantian.utils.JedisUtils;
import com.feri.tiantian.utils.NumUtils;
import com.feri.tiantian.utils.StringUtils;
import com.feri.tiantian.vo.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

import static com.feri.tiantian.config.SystemConfig.SMS_TYPE_LOGIN;

@Service
public class SmsLogServiceImpl implements SmsLogService {
    @Autowired
    private SmsLogDao smsLogDao;
    @Override
    public R sendLoginCode(String phone) {
        //1 校验
        if (StringUtils.isNoyEmpty(phone)){
            // 2 发送验证码
            int code = NumUtils.createNum(6);
            //3 发送
            if (AliSmsUtil.sendFCode(phone,code)) {
                //4 成功  存储 redis
                JedisUtils.setStr(RedisConfig.SMS_CODE_LOGIN + phone, code + "", RedisConfig.SMS_CODE_LOGIN_TIME);
                //5 保存数据到数据库中
                smsLogDao.insert(new SmsLog(phone,SMS_TYPE_LOGIN,"发送登陆的短信验证码",new Date()));
                return R.ok();//验证码不需要返回
            }
        }
        return    R.fail("发送失败");
    }

    //查询所有的发送过验证码的手机号
    @Override
    public R queryAll(String phone) {
        QueryWrapper<SmsLog> smsLogQueryWrapper = new QueryWrapper<>();
        //校验
        if (StringUtils.isNoyEmpty(phone)){
            smsLogQueryWrapper.eq("phone",phone);
        }
        //2 查询返回
        return R.ok(smsLogDao.selectList(smsLogQueryWrapper));
    }
}
